package com.dm.cloud.service.impl;

import com.dm.cloud.api.service.IKaptchaService;
import com.dm.cloud.common.R;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Objects;

@Slf4j
@Service
public class KaptchaServiceImpl implements IKaptchaService {

    @Autowired
    Producer kaptchaProducer;

    @Override
    public R create(HttpServletRequest request) {
        String text = kaptchaProducer.createText();
        BufferedImage image = kaptchaProducer.createImage(text);
        HttpSession session = request.getSession();
        session.setAttribute("kaptcha", text);
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "jpeg", outputStream);
            String base64 = Base64.getEncoder().encodeToString(outputStream.toByteArray());
            return R.success("data:image/jpeg;base64," + base64.replaceAll("\r\n", ""));
        } catch (IOException e) {
            //14001 验证码生成失败
            return R.failure(14001,"验证码生成失败");
        }
    }

    @Override
    public R checkImgCode(String code, HttpServletRequest request) {
        if (StringUtils.isBlank(code)) {
            //14002 验证码为空提示
            return R.failure(14002,"验证码不能空");
        }

        HttpSession session = request.getSession();
        String kaptcha = (String)session.getAttribute("kaptcha");
        if (null == kaptcha || Objects.requireNonNull(code).compareToIgnoreCase(kaptcha) != 0) {
            //14003 验证码不正确
            R result = R.failure(14003,"验证码不正确");
            result.setResult(create(request).getResult());
            return result;
        }
        return R.success();
    }
}
